package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import java.io.IOException;
import javafx.scene.control.Alert;
import java.sql.SQLException;
import java.util.List;
import java.util.Arrays;

public class LoginController {

    @FXML
    private TextField usernameField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private Button loginButton;

    private Stage primaryStage;
    private UserDAO userDAO;

    public void setPrimaryStage(Stage primaryStage) {
        if (primaryStage == null) {
            throw new IllegalArgumentException("primaryStage cannot be null");
        }
        this.primaryStage = primaryStage;
        
        System.out.println("LoginController primaryStage set: " + primaryStage);
    }

    @FXML
    public void initialize() {
        System.out.println("LoginController 初始化开始...");
        try {
            // 确保数据库已初始化
            System.out.println("正在初始化数据库...");
            DatabaseUtil.initializeDatabase();
            System.out.println("数据库初始化完成");
            
            userDAO = new UserDAO();
            System.out.println("UserDAO 创建成功");
            
            // 调用数据初始化方法，包括添加样本学生数据
            System.out.println("开始添加样本学生数据...");
            DataInitializer.addSampleStudents(userDAO);
            System.out.println("样本学生数据添加完成");
            
            // 调用班级重新分配方法
            System.out.println("开始重新分配班级...");
            reassignStudentClassesIfNecessary();
            System.out.println("班级重新分配完成");
            
            System.out.println("LoginController 初始化完成");
        } catch (Exception e) {
            System.err.println("LoginController 初始化失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    @FXML
    private void handleLogin() {
        String username = usernameField.getText();
        String password = passwordField.getText();

        System.out.println("尝试登录，用户名：" + username);

        if (username.isEmpty() || password.isEmpty()) {
            System.out.println("用户名或密码为空");
            showError("请输入用户名和密码");
            return;
        }

        try {
            System.out.println("正在查询用户：" + username);
            User user = userDAO.getUserByUsername(username);
            
            if (user == null) {
                System.out.println("用户不存在：" + username);
                showError("用户名不存在");
                return;
            }

            System.out.println("用户存在，正在验证密码");
            if (!user.getPassword().equals(password)) {
                System.out.println("密码错误：" + username);
                showError("密码错误");
                return;
            }

            System.out.println("正在检查用户状态");
            if (!"active".equals(user.getStatus())) {
                System.out.println("用户状态非活动：" + username);
                showError("该账号已被禁用");
                return;
            }

            System.out.println("登录成功，准备跳转到相应界面");
            // 登录成功，根据用户类型跳转到不同界面
            String fxmlFile;
            switch (user.getType()) {
                case "admin":
                    fxmlFile = "Admin.fxml";
                    break;
                case "teacher":
                    fxmlFile = "Teacher.fxml";
                    break;
                case "student":
                    fxmlFile = "Student.fxml";
                    break;
                default:
                    System.err.println("未知的用户类型：" + user.getType());
                    showError("未知的用户类型");
                    return;
            }

            System.out.println("正在加载界面：" + fxmlFile);
            FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlFile));
            Parent root = loader.load();

            Scene scene = new Scene(root);
            Stage stage = (Stage) loginButton.getScene().getWindow();
            stage.setScene(scene);
            stage.setTitle(user.getType() + "界面 - " + user.getName());

            // 获取控制器并设置当前用户
            Object controller = loader.getController();
            if (controller instanceof AdminController) {
                ((AdminController) controller).setPrimaryStage(stage);
            } else if (controller instanceof TeacherController) {
                ((TeacherController) controller).setPrimaryStage(stage);
                ((TeacherController) controller).setCurrentUser(user);
                System.out.println("已设置教师用户：" + user.getUsername());
            } else if (controller instanceof StudentController) {
                ((StudentController) controller).setPrimaryStage(stage);
                ((StudentController) controller).setCurrentUser(user);
                System.out.println("已设置学生用户：" + user.getUsername());
            }

            stage.show();
            System.out.println("界面加载完成并显示");

        } catch (SQLException e) {
            System.err.println("数据库错误：" + e.getMessage());
            e.printStackTrace();
            showError("数据库错误：" + e.getMessage());
        } catch (IOException e) {
            System.err.println("加载界面失败：" + e.getMessage());
            e.printStackTrace();
            showError("加载界面失败：" + e.getMessage());
        } catch (Exception e) {
            System.err.println("未知错误：" + e.getMessage());
            e.printStackTrace();
            showError("发生未知错误：" + e.getMessage());
        }
    }

    private void showError(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("登录错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    private void reassignStudentClassesIfNecessary() {
        try {
            List<User> students = userDAO.searchUsers(null, "student");
            System.out.println("找到 " + students.size() + " 个学生");
            
            for (User student : students) {
                if (student.getDepartment() == null || student.getDepartment().trim().isEmpty()) {
                    System.out.println("重新分配班级：" + student.getUsername());
                    // 根据学号分配班级
                    String department;
                    if (student.getUsername().startsWith("2023")) {
                        department = "软件工程1班";
                    } else if (student.getUsername().startsWith("2022")) {
                        department = "计算机科学2班";
                    } else {
                        department = "信息管理3班";
                    }
                    student.setDepartment(department);
                    userDAO.updateUser(student);
                    System.out.println("已将学生 " + student.getUsername() + " 分配到 " + department);
                }
            }
        } catch (SQLException e) {
            System.err.println("重新分配班级时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
} 